package com.ethanzzh.security.ethanzzhdemo.filter;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;


//拦截器是为了记录服务处理都时间
//可以拿到http请求方法的信息 也可以拿到处理到方法到信息，
//但是拿不到该方法的对象里面的参数值
//@Component
public class TimeInterceptor implements HandlerInterceptor {


    //object o 这个处理都controller里面对参数或者对象，是没有办法从中拿到相应属性到值  比如user的id什么；

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        System.out.println("preHandle");
        System.out.println(((HandlerMethod)o).getBean().getClass().getName());
        System.out.println(((HandlerMethod)o).getMethod().getName());
        httpServletRequest.setAttribute("startTime",new Date().getTime());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

        System.out.println("postHandle");
        Long start = (Long) httpServletRequest.getAttribute("startTime");
        System.out.println("interceptor耗时:" + (new Date().getTime() - start));


    }

    //无论最终有没有异常 都将会执行afterCompletion这个方法
    //定义了全局异常
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

        System.out.println("afterCompletion");
        Long start = (Long) httpServletRequest.getAttribute("startTime");
        System.out.println("耗时:" + (new Date().getTime() - start));
        System.out.println(" ex is " + e);
    }
}
